package edu.nctu.csie.jichang.database.app;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import edu.nctu.csie.jichang.database.command.DiffStructureCommand;
import edu.nctu.csie.jichang.database.command.ISQLCommand;
import edu.nctu.csie.jichang.database.dbinfo.DataBaseInfo;
import edu.nctu.csie.jichang.database.model.builder.AbstractSQLBuilder;
import edu.nctu.csie.jichang.database.model.cell.DBDatabase;
import edu.nctu.csie.jichang.database.parser.IParser;
import edu.nctu.csie.jichang.database.parser.ParseDDL;
import edu.nctu.csie.jichang.database.util.FileUtil;
import edu.nctu.csie.jichang.database.util.StringUtil;

public class DBUpgrade {

	private static final Logger LOG = LoggerFactory.getLogger(DBUpgrade.class);
	
	public static void main(String[] args) throws Exception{
		LOG.info("Strating - Database Upgrade ...");
		ApplicationContext tContext = new ClassPathXmlApplicationContext("dbtools.xml");
		DataBaseInfo tCurrentDatabase = tContext.getBean("current",DataBaseInfo.class);
		DataBaseInfo tBaseDatabase    = tContext.getBean("base",DataBaseInfo.class);
		IParser tParser = new ParseDDL();
		DBDatabase tCurrent = tParser.doParse(tCurrentDatabase.getLoginInfos());
		tCurrent.setDatabaseName("ienc");
		DBDatabase tBase = tParser.doParse(tBaseDatabase.getLoginInfos());
		tBase.setDatabaseName("base");
		ISQLCommand tCmd = new DiffStructureCommand();
		tCmd.setOperand(AbstractSQLBuilder.getSQLBuilder(tBaseDatabase.getLoginInfos().get(0)), tCurrent, tBase);
		String tSQL = tCmd.execute();
		LOG.info("Result = " + StringUtil.getMaxLength(tSQL, 60));
		FileUtil.writeStringToFile(tSQL, new File("output/"+tCurrentDatabase.getSchema()+".sql"));
		LOG.info("Finish - Database Upgrade ...");
	}
	
}
